package com.fengye.common.filter;

import com.fengye.common.constants.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author sunlei
 * @version 1.0
 * @date 2024/3/9 10:07:15
 * @description 自定义异常处理过滤器
 */
@Slf4j
@Component
public class CustomExceptionFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            log.error("Filter抛出了异常：{}", e.getMessage());
            // 传递异常信息
            request.setAttribute(CommonConstant.FILTER_ERROR_EXCEPTION_KEY, e);
            // 指定处理该请求的处理器
            request.getRequestDispatcher(CommonConstant.FILTER_ERROR_CONTROLLER_PATH).forward(request, response);
        }
    }
}
